package com.example.managemyself.data.network;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    private static final String WEATHER_BASE_URL = "https://api.open-meteo.com/";
    private static final String TIANAPI_BASE_URL = "https://apis.tianapi.com/";
    
    // 网络超时配置
    private static final int CONNECT_TIMEOUT = 15; // 连接超时15秒
    private static final int READ_TIMEOUT = 30;    // 读取超时30秒
    private static final int WRITE_TIMEOUT = 30;   // 写入超时30秒
    
    private static Retrofit weatherRetrofit = null;
    private static Retrofit tianApiRetrofit = null;
    private static OkHttpClient okHttpClient = null;

    /**
     * 获取配置好的OkHttpClient
     */
    private static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true) // 启用连接失败重试
                    .addInterceptor(loggingInterceptor)
                    .build();
        }
        return okHttpClient;
    }

    public static Retrofit getWeatherClient() {
        if (weatherRetrofit == null) {
            weatherRetrofit = new Retrofit.Builder()
                    .baseUrl(WEATHER_BASE_URL)
                    .client(getOkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return weatherRetrofit;
    }

    public static Retrofit getTianApiClient() {
        if (tianApiRetrofit == null) {
            tianApiRetrofit = new Retrofit.Builder()
                    .baseUrl(TIANAPI_BASE_URL)
                    .client(getOkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return tianApiRetrofit;
    }
}
